﻿using System;
using System.Net;
using System.Text;
using System.Threading;
using NUnit.Framework;
using Smith.AMC.Network;
using Smith.AMC.Operations;

namespace MemcachedClientTests
{
    [TestFixture]
    public class ClientSocketTest
    {
        [Test]
        public void TestSimpleStore()
        {
            IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11211);

            ClientSocket socket = new ClientSocket(ep, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);

            SetOperation operation = new SetOperation();
            operation.Key = "test";
            operation.Data = Encoding.UTF8.GetBytes("This is the new data");
            operation.Flags = (ushort) TypeCode.String;
            

            OperationResponse<string> operationResponse = null;
            ManualResetEvent evt = new ManualResetEvent(false);
            socket.BeginWrite<string>(
                operation,
                ar =>
                {
                    ManualResetEvent reset = (ManualResetEvent)ar.AsyncState;
                    try
                    {
                        operationResponse = socket.EndWrite<string>(ar);
                        
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                    finally
                    {
                        reset.Set();
                    }
                }, evt);

            evt.WaitOne();

            if (operationResponse != null)
            {
                Console.WriteLine(Encoding.ASCII.GetString(operationResponse.ServerResponse));
            }

            GetOperation get = new GetOperation();
            get.Key = "test";

            evt = new ManualResetEvent(false);
            socket.BeginWrite<string>(
                get,
                ar =>
                {
                    ManualResetEvent reset = (ManualResetEvent)ar.AsyncState;
                    try
                    {
                        operationResponse = socket.EndWrite<string>(ar);

                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                    finally
                    {
                        reset.Set();
                    }
                }, evt);

            evt.WaitOne();

            if (operationResponse != null)
            {
                Console.WriteLine(Encoding.ASCII.GetString(operationResponse.ServerResponse));
            }
        }
    }
}
